﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace NewBee.Core.Data.SQLBuilder
{
    public class Delete
    {
        private static string DELETE_SQL = @"DELETE FROM {0} WHERE {1}";//删除语句
        private DbHelper _DbHelper = null;//数据操作类

        private string _TableName = string.Empty;//表名
        private string _Where = string.Empty;   //条件
        private object _Parameter; //参数
        private DynamicParameters _Parameters=new DynamicParameters();  //参数

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="dbHelper"></param>
        /// <param name="tableName"></param>
        public Delete(DbHelper dbHelper,string tableName)
        {
            _DbHelper = dbHelper;
            _TableName = tableName;
        }

        /// <summary>
        /// 条件语句
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public Delete Where(string where)
        {
            _Where = where;
            return this;
        }

        public Delete Parameter(object param)
        {
            _Parameter = param;
            return this;
        }
        /// <summary>
        /// 参数
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public Delete Parameters(params object[] parameters)
        {
            if (parameters != null)
            {
                for (var i = 0; i < parameters.Count(); i++) {
                    _Parameters.Add("@" + i, parameters[i]==null?0: parameters[i]);
                }
            }
            
            return this;
        }

        /// <summary>
        /// 执行删除
        /// </summary>
        /// <returns></returns>
        public int Execute()
        {
            if (string.IsNullOrEmpty(_Where))
                _Where = " 1=1 ";

            string sql = string.Format(DELETE_SQL, _TableName, _Where);
            
            return _DbHelper.Execute(sql, _Parameter==null?_Parameters: _Parameter);
        }


    }
}
